package cs2013;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class User_To_Item {
	static Map<String, ArrayList<String>> user_to_item = new HashMap<String, ArrayList<String>>();
	
	public User_To_Item() throws IOException {
		
		FileInputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		fis = new FileInputStream("src/cs2013/ratings_train_test.txt");
		isr = new InputStreamReader(fis);
		br = new BufferedReader(isr);

		while (br.ready()) {
			String lineTxt = br.readLine();
			String UserID, MovieID, Rating;
			String[] stp = lineTxt.split("::");
			UserID = stp[0];
			MovieID = stp[1];
			Rating = stp[2];
			if(!user_to_item.containsKey(UserID)){
				ArrayList<String> arr = new ArrayList<String>();
				arr.add(MovieID + ":" + Rating);
				user_to_item.put(UserID, arr);
			}
			else
			{
				user_to_item.get(UserID).add(MovieID+":"+Rating);
			}
		}				
		fis.close();
		isr.close();
		br.close();
		
		
		File file;
		FileWriter fw;
		PrintWriter pw;

		file = new File("src/cs2013/user_to_item.txt");
		if (!file.exists()){
			file.createNewFile();
		}
		fw = new FileWriter(file);
		pw = new PrintWriter(fw);
		
		
		Set set = user_to_item.keySet();
        Iterator<String> it = set.iterator();                                                                                                
		while(it.hasNext()){
			String result=(String)it.next();
            ArrayList<String> st = user_to_item.get(result);			
			for(int i = 0; i < st.size() ;i ++)
			{	
			     pw.println(st.get(i));
			}	
		}	
		pw.close();

	}
	
	public ArrayList get(String userid){
		return user_to_item.get(userid);
	}
		

}
